package com.ruoyi.rabbit.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.wp.WpArticlesStatus;
import com.ruoyi.common.enums.wp.WpTasksStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TextUtils;
import com.ruoyi.rabbit.service.ManageRabbitService;
import com.ruoyi.rabbit.service.RabbitSenderService;
import com.ruoyi.system.domain.DictCategory;
import com.ruoyi.system.domain.DictKeywordTitle;
import com.ruoyi.system.domain.OpenaiMsg;
import com.ruoyi.system.domain.OpenaiMsgGroups;
import com.ruoyi.system.openai.RequestOpenAi;
import com.ruoyi.system.service.IDictCategoryService;
import com.ruoyi.system.service.IDictKeywordTitleService;
import com.ruoyi.system.service.IOpenaiMsgGroupsService;
import com.ruoyi.system.service.IOpenaiMsgService;
import com.ruoyi.tasks.domain.WpTasks;
import com.ruoyi.tasks.service.IWpTasksService;
import com.ruoyi.wp.domain.WpArticles;
import com.ruoyi.wp.service.IWpArticlesService;
import com.ruoyi.wp.service.IWpKeyCategoryService;
import com.unfbx.chatgpt.entity.chat.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ManageRabbitServiceImpl implements ManageRabbitService {

    @Autowired
    IWpTasksService iWpTasksService;
    @Autowired
    IOpenaiMsgGroupsService iOpenaiMsgGroupsService;
    @Autowired
    IOpenaiMsgService iOpenaiMsgService;
    @Autowired
    RabbitSenderService rabbitSenderService;
    @Autowired
    RequestOpenAi requestOpenAi;
    @Autowired
    IDictKeywordTitleService iDictKeywordTitleService;
    @Autowired
    IDictCategoryService iDictCategoryService;
    @Autowired
    IWpArticlesService iWpArticlesService;
    @Autowired
    IWpKeyCategoryService iWpKeyCategoryService;


    @Override
    public void wpTasks(String json) {

        if (StringUtils.isNull(json)){
            System.out.println("MQ获取参数值错误，json参数为空！");
            return;
        }
        JSONObject data = JSON.parseObject(json);
        WpTasks tasks = JSONObject.parseObject(data.getString("wpTasks"),WpTasks.class);
        Integer wpTasksId = tasks.getId();
        Long openaiMsgGroupsId= tasks.getOpenaiMsgGroupsId();

        WpTasks wpTasks = iWpTasksService.selectWpTasksById(wpTasksId);
        if (wpTasks == null){
            System.out.println("脏数据wpTasks为空！wpTasksId值为"+wpTasksId);
            return;
        }
        OpenaiMsgGroups openaiMsgGroups = iOpenaiMsgGroupsService.selectOpenaiMsgGroupsById(openaiMsgGroupsId);
        if(openaiMsgGroups==null){
            System.out.println("脏数据openaiMsgGroups为空！openaiMsgGroupsId值为"+openaiMsgGroupsId);
            return;
        }
        OpenaiMsg openaiMsg = new OpenaiMsg();
        openaiMsg.setOpenaiMsgGroupsId(openaiMsgGroupsId);
        List<OpenaiMsg> msgList = iOpenaiMsgService.selectOpenaiMsgList(openaiMsg);
        if (msgList==null || msgList.size() == 0){
            System.out.println("openaiMsgGroupsId数据未找到！请检查数据库是否有对应的值！");
            return;
        }
        //查询总请求次数，请求防止请求次数过多阻塞线程
        Integer repetitionsCompleted = wpTasks.getRepetitionsCompleted();
        System.out.println("wpTasks.repetitionsCompleted的总请求次数为==========");
        System.out.println(repetitionsCompleted);
        System.out.println("===================================");

        //查询创建标题的对话组关键词，防止放在循环里面增加查询
        DictCategory dictCategory = new DictCategory();
        dictCategory.setParentId(wpTasks.getTasksOption());
        List<DictCategory> dictCategoryList = iDictCategoryService.selectDictCategoryList(dictCategory);
        if (dictCategoryList==null || dictCategoryList.size() == 0){
            System.out.println("dictCategoryList数据未找到！请检查数据库的创建文章标题字段是否被删除！");
            return;
        }
        WpTasks updateTasks = new WpTasks();
        updateTasks.setId(wpTasksId);
        updateTasks.setStatus(WpTasksStatus.IN_EXECUTE.getCode());
        iWpTasksService.updateWpTasks(updateTasks);


        for(int i = 0; i< repetitionsCompleted ; i++){

            JSONObject titleData = new JSONObject();
            titleData.put("totalRepetitions",wpTasks.getTotalRepetitions());
            titleData.put("wpTasksId",wpTasks.getId());
            titleData.put("wpTasks",wpTasks);
            titleData.put("msgList",msgList);
            titleData.put("dictCategoryList",dictCategoryList);
            rabbitSenderService.sendDictTitle(titleData.toString());

        }


    }

    @Override
    public void manageDictTitle(String json) {
        JSONObject data = JSON.parseObject(json);
        Integer totalRepetitions = data.getInteger("totalRepetitions");
        Integer wpTasksId = data.getInteger("wpTasksId");
        WpTasks wpTasks = JSONObject.parseObject(data.getString("wpTasks"),WpTasks.class);
        List<OpenaiMsg> openaiMsgList = JSON.parseArray(data.getJSONArray("msgList").toJSONString(), OpenaiMsg.class);
        List<DictCategory> dictCategoryList = JSON.parseArray(data.getJSONArray("dictCategoryList").toJSONString(), DictCategory.class);

        //查询数据库最新的状态，防止出现数据不一致问题
        WpTasks newsTasks = iWpTasksService.selectWpTasksById(wpTasks.getId());
        if(newsTasks.getRepetitionsCompleted()!=null &&
                newsTasks.getRepetitionsCompleted()>=wpTasks.getRepetitionsPerRequest()){
            System.out.println("任务已完成！重复次数到此结束！");
            return;
        }

        for (int i = 0 ;i< totalRepetitions ; i++){
            //组装参数给GPT
            List<Message> messages = new ArrayList<>();

            String template = openaiMsgList.get(0).getMessageContent();

            //按照顺序生成获取下标值
            int dictIndex = i % dictCategoryList.size();
            DictCategory dictCategory = dictCategoryList.get(dictIndex);

            String sendString = String.format(template,totalRepetitions,dictCategory.getCategoryName());

            Message currentMessage = Message.builder().content(sendString).role(Message.Role.USER).build();
            messages.add(currentMessage);

            List<Message> gptMsg = requestOpenAi.sendGPT(messages);
            if(gptMsg==null || gptMsg.size()==0){
                return;
            }
            String content = gptMsg.get(0).getContent();
            // 输出处理后的标题
            String[] titleArray = content.split("\n");

            for (String title : titleArray) {
                // 移除数字编号
                String[] splitTitle = title.split(". ", 2);
                String noNumberTitle = splitTitle[splitTitle.length - 1];

                // 替换中文冒号为逗号
                String fixedTitle = noNumberTitle.replace("：", "，").replace("\"","").replace("”","");

                DictKeywordTitle dictKeywordTitle = new DictKeywordTitle();
                dictKeywordTitle.setTitle(fixedTitle);
                dictKeywordTitle.setUserId(wpTasks.getUserId());
                dictKeywordTitle.setCategoryId(dictCategory.getId());
                dictKeywordTitle.setCategoryParentId(dictCategory.getParentId());
                iDictKeywordTitleService.insertDictKeywordTitle(dictKeywordTitle);
            }
        }

        this.updateTasks(wpTasks,newsTasks);
    }

    @Override
    public void createArticles(String json) {
        if (StringUtils.isNull(json)){
            System.out.println("MQ获取参数值错误，json参数为空！");
            return;
        }
        JSONObject data = JSON.parseObject(json);
        WpTasks wpTasks = JSONObject.parseObject(data.getString("wpTasks"),WpTasks.class);
        DictKeywordTitle dictKeywordTitle = JSONObject.parseObject(data.getString("dictKeywordTitle"),DictKeywordTitle.class);
        List<OpenaiMsg> msgList = JSON.parseArray(data.getJSONArray("msgList").toJSONString(), OpenaiMsg.class);

        //查询数据库最新的状态，防止出现数据不一致问题
        WpTasks newsTasks = iWpTasksService.selectWpTasksById(wpTasks.getId());
        if(newsTasks.getRepetitionsCompleted()!=null &&
                newsTasks.getRepetitionsCompleted()>=wpTasks.getRepetitionsPerRequest()){
            System.out.println("任务已完成！重复次数到此结束！");
            return;
        }

        //组装参数给GPT
        List<Message> messages = new ArrayList<>();

        for (int i = 0 ; i<msgList.size() ; i++){
            OpenaiMsg msg = msgList.get(i);
            String sendString = null;
            //替换值
            if(msg.getMessageContent().contains("%s")){
                sendString = String.format(msg.getMessageContent(),dictKeywordTitle.getTitle());
            }else{
                sendString = msg.getMessageContent();
            }

            Message currentMessage = Message.builder().content(sendString).role(Message.Role.USER).build();
            messages.add(currentMessage);
        }

        List<Message> gptMsg = requestOpenAi.sendGPT(messages);
        if(gptMsg==null || gptMsg.size()==0){
            throw new ServiceException("openai请求出错，gptMsg参数返回异常！");
        }
        String content = gptMsg.get(0).getContent();
        //TODO 关键词提炼

        //切割文字排版
        String reformatText = TextUtils.reformatText(content);

        //组装文章参数
        WpArticles wpArticles = new WpArticles();
        wpArticles.setUserId(wpTasks.getUserId());
        wpArticles.setTitle(dictKeywordTitle.getTitle());
        wpArticles.setContent(reformatText);
        wpArticles.setStatus(WpArticlesStatus.TO_ISSUE.getCode());
        wpArticles.setCategoryId(wpTasks.getTasksOption());
        iWpArticlesService.insertWpArticles(wpArticles);

        this.updateTasks(wpTasks,newsTasks);
    }

    /**
     * 更新任务状态
     * */
    void updateTasks(WpTasks wpTasks,WpTasks newsTasks){

        Integer repetitionsCompleted = null;
        if(newsTasks.getRepetitionsCompleted()==null || newsTasks.getRepetitionsCompleted()==0){
            repetitionsCompleted = 1;
        }else{
            repetitionsCompleted = newsTasks.getRepetitionsCompleted()+1;
        }

        WpTasks updateTasks = new WpTasks();
        updateTasks.setId(wpTasks.getId());
        updateTasks.setRepetitionsCompleted(repetitionsCompleted);

        if(newsTasks.getRepetitionsPerRequest().equals(repetitionsCompleted)){
            updateTasks.setStatus(WpTasksStatus.SUCCESS.getCode());
        }
        iWpTasksService.updateWpTasks(updateTasks);

    }


}
